package tk.mybatis.springboot.service;

import tk.mybatis.springboot.mapper.UserInfoMapper;
import tk.mybatis.springboot.model.UserInfo;

import java.util.List;
import java.util.concurrent.RecursiveTask;

public class UserInfoSaveTask extends RecursiveTask<Integer> {

    static final int THRESHOLD = 2;
    List<UserInfo> array;
    int start;
    int end;
    UserInfoMapper userInfoMapper;

    UserInfoSaveTask(List<UserInfo> array, int start, int end, UserInfoMapper userInfoMapper) {
        this.array = array;
        this.start = start;
        this.end = end;
        this.userInfoMapper = userInfoMapper;
    }

    @Override
    protected Integer compute() {
        if (end - start <= THRESHOLD) {
            // 如果任务足够小,直接计算:
            int sum = userInfoMapper.insertList(array.subList(start,end));
            System.out.println(String.format("compute %d~%d = %d", start, end, sum));
            return sum;
        }
        // 任务太大,一分为二:
        int middle = (end + start) / 2;
        System.out.println(String.format("split %d~%d ==> %d~%d, %d~%d", start, end, start, middle, middle, end));
        UserInfoSaveTask subtask1 = new UserInfoSaveTask(this.array, start, middle, userInfoMapper);
        UserInfoSaveTask subtask2 = new UserInfoSaveTask(this.array, middle, end, userInfoMapper);
        invokeAll(subtask1, subtask2);
        int subresult1 = subtask1.join();
        int subresult2 = subtask2.join();
        int result = subresult1 + subresult2;
        System.out.println("result = " + subresult1 + " + " + subresult2 + " ==> " + result);
        return result;
    }
}
